#!/bin/sh

. "$SPEC_PATH/abstract/dbops-major-version-upgrade"

e2e_test_extra_hash() {
  "$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" path_hash \
    "$(realpath --relative-to "$PROJECT_PATH" "$SPEC_PATH/abstract/dbops-major-version-upgrade")"
}

e2e_test() {
  run_test "Checking that major version upgrade timeout works correctly" check_major_version_upgrade_timed_out

  run_test "Checking that major version upgrade can be repeated if failed" check_major_version_upgrade_repeat
}

check_major_version_upgrade_timed_out() {
  reset_cluster

  cat << EOF | kubectl create -f -
apiVersion: stackgres.io/v1
kind: SGDbOps
metadata:
  name: $DBOPS_NAME
  namespace: $CLUSTER_NAMESPACE
spec:
  sgCluster: $CLUSTER_NAME
  op: majorVersionUpgrade
  timeout: PT1S
  majorVersionUpgrade:
    postgresVersion: "$E2E_MAJOR_TARGET_POSTGRES_VERSION"
    sgPostgresConfig: postgresconf-for-major-version-upgrade
    postgresExtensions:
    - name: pg_repack
      version: $TARGET_PG_REPACK_VERSION
EOF

  if kubectl wait --timeout "$((E2E_TIMEOUT * 2))s" -n "$CLUSTER_NAMESPACE" sgdbops "$DBOPS_NAME" \
    --for condition=Completed \
    && kubectl wait --timeout 0s -n "$CLUSTER_NAMESPACE" sgdbops "$DBOPS_NAME" \
    --for condition=Failed
  then
    success "major version upgrade failed."
  else
    fail "major version upgrade did not fail."
  fi

  if [ "$(kubectl get -n "$CLUSTER_NAMESPACE" job \
    -l "stackgres.io/dbops-name=$DBOPS_NAME,stackgres.io/db-ops=true" \
    -o name 2>/dev/null | wc -l)" = 1 ]
  then
    success "major version upgrade job was not removed after failure."
  else
    fail "major version upgrade job was removed after failure."
  fi

  kubectl delete sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME"

  if wait_until eval '[ "$(kubectl get -n "$CLUSTER_NAMESPACE" job \
    -l "stackgres.io/dbops-name=$DBOPS_NAME,stackgres.io/db-ops=true" \
    -o name 2>/dev/null | wc -l)" = 0 ]'
  then
    success "major version upgrade job was removed after sgdbops was removed."
  else
    fail "major version upgrade job was not removed after sgdbops was removed."
  fi

  check_mock_data_samehost "$CLUSTER_NAME"
  wait_until check_mock_data_replication "$CLUSTER_NAME"
}

check_major_version_upgrade_repeat() {
    cat << EOF | kubectl create -f -
apiVersion: stackgres.io/v1
kind: SGDbOps
metadata:
  name: $DBOPS_NAME
  namespace: $CLUSTER_NAMESPACE
spec:
  sgCluster: $CLUSTER_NAME
  op: majorVersionUpgrade
  majorVersionUpgrade:
    postgresVersion: "$E2E_MAJOR_TARGET_POSTGRES_VERSION"
    sgPostgresConfig: postgresconf-for-major-version-upgrade
    postgresExtensions:
    - name: pg_repack
      version: $TARGET_PG_REPACK_VERSION
EOF

  check_major_version_upgrade

  kubectl delete sgdbops -n "$CLUSTER_NAMESPACE" "$DBOPS_NAME"
}
